package cn.linjianhui.cluster.service.impl;

import cn.linjianhui.cluster.dao.RedPacketDao;
import cn.linjianhui.cluster.dao.UserRedPacketDao;
import cn.linjianhui.cluster.pojo.UserRedPacket;
import cn.linjianhui.cluster.service.RedisRedPacketService;
import com.sun.jmx.snmp.Timestamp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

@Service
public class RedisRedPacketServiceImpl implements RedisRedPacketService {

    @Autowired
    private RedisTemplate<String, String>  redisTemplate;

    @Autowired
    private UserRedPacketDao userRedPacketDao;

    private static final int TIME_SIZE = 1000;

    private static final String PREFIX = "red_packet_list_";

    @Override
    @Async
    public void saveUserRedPacketByRedis(Long redPackId, Double unitAmount) {

        System.err.println("开始保存数据");
        long start = System.currentTimeMillis();

        String redPacketKey = String.format("%s{%d}", PREFIX, redPackId);

        BoundListOperations<String, String> ops = redisTemplate.boundListOps(redPacketKey);
        Long size = ops.size();
        Long time = size % TIME_SIZE == 0 ? size/TIME_SIZE : (size/TIME_SIZE + 1);
        int count = 0;
        List<UserRedPacket> saveObjects = new ArrayList<>();
        for(int i = 0; i < time; i++) {
            List<String> userIds;
            if(i == 0) {
                userIds = ops.range(0, TIME_SIZE);
            }else {
                userIds = ops.range(i*TIME_SIZE+1, (i+1)*TIME_SIZE);
            }
            saveObjects.clear();
            for(int j = 0; j < userIds.size(); j++) {
                String[] args = userIds.get(j).split("-");
                Long userId = Long.parseLong(args[0]);
                Long timestamp = Long.parseLong(args[1]);

                UserRedPacket packet = new UserRedPacket();
                packet.setUserId(userId);
                packet.setRedPacketId(redPackId);
                packet.setAmount(unitAmount);
                packet.setGrabTime(LocalDateTime.ofInstant(
                        Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()));

                saveObjects.add(packet);
            }

            count += userRedPacketDao.batchInsertUserRedPacket(saveObjects);
        }

        redisTemplate.delete(redPacketKey);
        long end = System.currentTimeMillis();
        System.err.println(String.format("保存数据结束，耗时：%d，共有 %d 条数据保存成功", end-start, count));
    }
}
